package com.traveldream.entity_managers;

import java.util.ArrayList;
import java.util.List;

import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import com.traveldream.entities.Place;

/**
 * Session Bean implementation class PlaceManagerBean
 */
@Stateless
public class PlaceManagerBean implements PlaceManager {
	
	// bisogna indicare che si usa la persistenza configurata nel package Common
	@PersistenceContext(unitName="TravelDreamCommon")
    EntityManager em;
	
	@Override
	public List<Place> findAll() {
		Query query = em.createNamedQuery("Place.findAll",Place.class);
    	List<Place> results=new ArrayList<Place>();
   		for( Object o : query.getResultList() ) 
   			results.add((Place)o);
		return results;
	}

	@Override
	public Place find(String name) {
		return em.find(Place.class, name);
	}

	@Override
	public List<Place> findByInitials(String init) {
		Query query = em.createNamedQuery("Place.findByInitials",Place.class).setParameter("init", init+"_%");
    	List<Place> results=new ArrayList<Place>();
   		for( Object o : query.getResultList() ) 
   			results.add((Place)o);
		return results;
	}
	
	public void create(Place p)
	{
		if(em.find(Place.class, p.getName())==null)
				em.persist(p);
		em.flush();
	}
	
	public void update(Place p)
	{
		em.merge(p);
		em.flush();
	}

}
